package com.codingke.codingbookstore.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.codingke.codingbookstore.App;
import com.codingke.codingbookstore.R;
import com.codingke.codingbookstore.ui.AddressManagerActivity;
import com.codingke.codingbookstore.ui.LoginActivity;
import com.codingke.codingbookstore.ui.MainActivity;
import com.codingke.codingbookstore.ui.OrdersActivity;
import com.codingke.codingbookstore.utils.AppUtils;
import com.codingke.codingbookstore.utils.Constant;
import com.codingke.codingbookstore.vo.User;
import com.github.siyamed.shapeimageview.CircularImageView;

import java.io.File;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * descreption:
 * company: codingke.com
 * Created by vince on 15/11/13.
 */
public class PersonalFragment extends BaseFragment implements View.OnClickListener{

    private static final int REQUEST_CODE_LOGIN = 0x100;//打开登录界面的请求码
    private static final int PHOTO_REQUEST_CUT = 0x200;//打开图库的请求码
    private Button textView3_login;
    private TextView textView2_username;
    private MainActivity mainActivity;
    private CircularImageView imageView_userIcon;
    private User currentUser;
    private LinearLayout exit_layout;
    private Button button_user_address;
    private File tempImage; //裁剪后的图片


    private LinearLayout all_orders_layout,wait_pay_layout,wait_goodsReceipt_layout,wait_Evaluation_layout;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mainActivity = (MainActivity) getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_personal,null);
        textView3_login = (Button) view.findViewById(R.id.textView3_login);
        textView3_login.setOnClickListener(this);
        textView2_username = (TextView) view.findViewById(R.id.textView2_username);
        exit_layout = (LinearLayout) view.findViewById(R.id.exit_layout);
        exit_layout.setOnClickListener(this);
        imageView_userIcon = (CircularImageView) view.findViewById(R.id.imageView_userIcon);
        imageView_userIcon.setOnClickListener(this);
        button_user_address = (Button) view.findViewById(R.id.button_user_address);
        button_user_address.setOnClickListener(this);

        all_orders_layout = (LinearLayout) view.findViewById(R.id.all_orders_layout);
        wait_pay_layout = (LinearLayout) view.findViewById(R.id.wait_pay_layout);
        wait_goodsReceipt_layout = (LinearLayout) view.findViewById(R.id.wait_goodsReceipt_layout);
        wait_Evaluation_layout = (LinearLayout) view.findViewById(R.id.wait_Evaluation_layout);
        all_orders_layout.setOnClickListener(this);
        wait_pay_layout.setOnClickListener(this);
        wait_goodsReceipt_layout.setOnClickListener(this);
        wait_Evaluation_layout.setOnClickListener(this);

        tempImage = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + Constant.CACHE_PATH + "/user_portrait.jpg");

        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.textView3_login:
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                //startActivity(intent);
                startActivityForResult(intent, REQUEST_CODE_LOGIN);
                break;
            case R.id.exit_layout:
                logOut();
                break;
            case R.id.button_user_address:
                addressManager();
                break;
            case R.id.imageView_userIcon:
                selectIcon();
                break;
            case R.id.all_orders_layout:
                //所有订单
                allOrders();
                break;
            case R.id.wait_pay_layout:
                //待付款
                waitPayOrders();
                break;
            case R.id.wait_goodsReceipt_layout:
                //待收货
                waitGoodsReceipt();
                break;
            case R.id.wait_Evaluation_layout:
                //待评价
                waitEvaluation();
                break;
            default:
                break;
        }

    }

    private void waitEvaluation() {
        viewOrders(OrdersActivity.VIEW_WAIT_EVALUATION_ORDERS);
    }

    private void waitGoodsReceipt() {
        viewOrders(OrdersActivity.VIEW_WAIT_GOODS_RECEIPT_ORDERS);
    }

    private void waitPayOrders() {
        viewOrders(OrdersActivity.VIEW_WAIT_PAY_ORDERS);
    }

    private void allOrders() {
        viewOrders(OrdersActivity.VIEW_ALL_ORDERS);
    }


    private void viewOrders(int status){
        if (currentUser==null){
            mainActivity.showToast("请登录后再查看订单");
            startActivity(new Intent(mainActivity,LoginActivity.class));
            return;
        }
        Intent intent = new Intent(mainActivity, OrdersActivity.class);
        intent.putExtra("status",status);
        startActivity(intent);
    }



    private void addressManager() {
        startActivity(new Intent(mainActivity, AddressManagerActivity.class));
    }

    @Override
    public void onResume() {
        super.onResume();
        currentUser = BmobUser.getCurrentUser(mainActivity,User.class);
        updateLoginStatus();
    }

    //退出登录
    private void logOut() {
        currentUser = null;
        User.logOut(mainActivity);
        updateLoginStatus();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(Activity.RESULT_OK==resultCode && REQUEST_CODE_LOGIN==requestCode){
            //更新登录状态
            updateLoginStatus();
        }
        else if (Activity.RESULT_OK == resultCode && PHOTO_REQUEST_CUT == requestCode) {
            if (tempImage.exists()) {
                final BmobFile bmobFile = new BmobFile(tempImage);
                bmobFile.upload(mainActivity, new UploadFileListener() {
                    @Override
                    public void onSuccess() {
                        currentUser.setUserIcon(bmobFile);
                        currentUser.update(mainActivity, new UpdateListener() {
                            @Override
                            public void onSuccess() {
                                //App.bitmapUtils.display(imageView_userIcon,tempImage.getAbsolutePath());
                                updateLoginStatus();
                                mainActivity.showToast("头像更新成功");
                            }

                            @Override
                            public void onFailure(int i, String s) {
                                mainActivity.showToast("头像更新失败" + s);
                            }
                        });

                    }

                    @Override
                    public void onFailure(int i, String s) {
                        mainActivity.showToast("头像更新失败");
                    }
                });

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 更新登录状态
     */
    private void updateLoginStatus() {
        System.out.println("updateLoginStatus");
        if(currentUser!=null){
            textView3_login.setVisibility(View.GONE);//登录按钮
            imageView_userIcon.setVisibility(View.VISIBLE);//头像
            textView2_username.setVisibility(View.VISIBLE);//用户名(手机号)
            exit_layout.setVisibility(View.VISIBLE);//退出按钮
            button_user_address.setVisibility(View.VISIBLE);//收货地址

            textView2_username.setText(AppUtils.formatPhoneNumber(currentUser.getUsername()));
            if(currentUser.getUserIcon()!=null) {
                App.bitmapUtils.display(imageView_userIcon, Constant.BMOBFILE_ROOT+currentUser.getUserIcon().getUrl());
            }else{
                imageView_userIcon.setImageResource(R.mipmap.de_default_portrait);
            }
        }else{
            textView3_login.setVisibility(View.VISIBLE);
            imageView_userIcon.setVisibility(View.GONE);
            textView2_username.setVisibility(View.GONE);
            exit_layout.setVisibility(View.GONE);
            button_user_address.setVisibility(View.GONE);
        }
    }

    /**
     * 打开系统图库,选择图片并裁剪
     */
    private void selectIcon() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempImage));
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }
}
